<template>
  <div class="dashboard-container">
    <!-- 警告 -->
    <el-row v-if="warningList.length" class="warning-row" style="margin-bottom: 20px;">
      <el-col :span="24">
        <el-alert
          :title="$t('dashboard.orderRemarkWarning', { days: warningDays })"
          type="warning"
          show-icon
          :closable="false"
        >
          <div class="warning-header">
            <span>{{$t('dashboard.warningDays')}}：</span>
            <el-input-number v-model="warningDays" :min="1" :max="30" size="small" :step="1" style="width: 100px;" />
            <span class="warning-tip">{{$t('dashboard.adjustable')}}</span>
          </div>
          <ul class="warning-list">
            <li v-for="item in warningList" :key="item.type + '-' + item.id">
              <span class="order-type">[{{ item.type === 'local' ? $t('dashboard.typeLocal') : $t('dashboard.typeTransfer') }}]</span>
              <span class="order-id">
                {{$t('dashboard.orderNo')}}：
                <el-tooltip :content="$t('dashboard.copy')" placement="top">
                  <span class="copy-text" @click="copyText(item.no)">{{ item.no }}</span>
                </el-tooltip>
              </span>
              <span class="order-user">{{$t('dashboard.createUser')}}：{{ item.create_user }}</span>
              <span class="order-date">{{$t('dashboard.createDate')}}：{{ item.create_time }}</span>
            </li>
          </ul>
        </el-alert>
      </el-col>
    </el-row>
    <!-- 备注 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card local-card">
          <div slot="header" class="clearfix">
            <span class="card-title">{{$t('dashboard.localRemark')}}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshLocalRemarks">{{$t('dashboard.refresh')}}</el-button>
          </div>
          <div v-loading="localLoading">
            <div v-if="filteredLocalRemarks.length === 0" class="empty-text">{{$t('dashboard.noRemark')}}</div>
            <div v-else class="remark-list">
              <div v-for="(item, index) in filteredLocalRemarks" :key="index" class="remark-item">
                <div class="remark-header">
                  <span class="order-id">
                    {{$t('dashboard.orderNo')}}：
                    <el-tooltip :content="$t('dashboard.copy')" placement="top">
                      <span class="copy-text" @click="copyText(item.fs_no)">{{ item.fs_no }}</span>
                    </el-tooltip>
                  </span>
                  <span class="remark-time">{{ formatTime(item.create_time) }}</span>
                </div>
                <div class="remark-content">{{ item.remark }}</div>
                <div class="remark-footer">
                  <span class="create-user">{{$t('dashboard.createUser')}}：{{ item.create_user }}</span>
                  <span class="shipping-method" :class="item.shipping_method.toLowerCase()">{{ item.shipping_method }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card transfer-card">
          <div slot="header" class="clearfix">
            <span class="card-title">{{$t('dashboard.transferRemark')}}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshTransferRemarks">{{$t('dashboard.refresh')}}</el-button>
          </div>
          <div v-loading="transferLoading">
            <div v-if="filteredTransferRemarks.length === 0" class="empty-text">{{$t('dashboard.noRemark')}}</div>
            <div v-else class="remark-list">
              <div v-for="(item, index) in filteredTransferRemarks" :key="index" class="remark-item">
                <div class="remark-header">
                  <span class="order-id">
                    {{$t('dashboard.orderNo')}}：
                    <el-tooltip :content="$t('dashboard.copy')" placement="top">
                      <span class="copy-text" @click="copyText(item.cw_no)">{{ item.cw_no }}</span>
                    </el-tooltip>
                  </span>
                  <span class="remark-time">{{ formatTime(item.create_time) }}</span>
                </div>
                <div class="remark-content">{{ item.remark }}</div>
                <div class="remark-footer">
                  <span class="create-user">{{$t('dashboard.createUser')}}：{{ item.create_user }}</span>
                  <span class="shipping-method" :class="item.shipping_method.toLowerCase()">{{ item.shipping_method }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 待办事项 -->
    <el-row :gutter="20" style="margin-top: 30px;">
      <el-col :span="24">
        <el-card class="todo-card">
          <div slot="header" class="clearfix">
            <span class="card-title">{{$t('dashboard.todo')}}</span>
          </div>
          <div class="todo-list">
            <el-form @submit.native.prevent="addTodo">
              <el-input
                v-model="newTodo"
                :placeholder="$t('dashboard.todoPlaceholder')"
                @keyup.enter.native="addTodo"
                class="todo-input"
                clearable
              />
            </el-form>
            <div class="todo-cards-container">
              <div v-for="(item, idx) in todos" :key="item.id" class="todo-card-item" :class="{done: item.done}">
                <div class="todo-card-content">
                  <div class="todo-text">{{ item.description }}</div>
                  <div class="todo-meta">
                    <span class="todo-creator">{{ item.created_by }}创建</span>
                    <el-button type="text" icon="el-icon-delete" @click="removeTodo(idx)" class="todo-delete"></el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="todos.length === 0" class="todo-empty">{{$t('dashboard.noTodo')}}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 日历 -->
    <el-row :gutter="20" style="margin-top: 30px;">
      <el-col :span="24">
        <el-card class="calendar-card">
          <div slot="header" class="clearfix">
            <span class="card-title">{{$t('dashboard.calendar')}}</span>
          </div>
          <el-calendar v-model="calendarDate" class="dashboard-calendar">
            <template slot="dateCell" slot-scope="{ date }">
              <div class="calendar-date-cell">
                <span :class="['calendar-date', isToday(date) ? 'today' : '']">{{ date.getDate() }}</span>
                <span v-if="getJpHoliday(date)" class="jp-holiday">{{ getJpHoliday(date) }}</span>
                <ul class="calendar-events">
                  <li v-for="(item, idx) in getEventsByDate(date)" :key="idx" :class="item.type">
                    <el-tooltip :content="item.content" placement="top">
                      <span class="event-dot" :style="{background: eventTypeColor(item.type)}"></span>
                    </el-tooltip>
                  </li>
                </ul>
              </div>
            </template>
          </el-calendar>
          <div class="calendar-event-panel">
            <div class="event-panel-header">
              <span>【{{ calendarDate | formatDate }}】{{$t('dashboard.calendarPanel')}}</span>
              <el-button type="primary" size="mini" @click="showAddEventDialog = true">{{$t('dashboard.addEvent')}}</el-button>
            </div>
            <ul class="event-list">
              <li v-for="(item, idx) in getEventsByDate(calendarDate)" :key="idx" :class="item.type">
                <span class="event-dot" :style="{background: eventTypeColor(item.type)}"></span>
                <span class="event-title">{{ item.title }}</span>
                <span class="event-type">（{{ eventTypeLabel(item.type) }}）</span>
                <el-button type="text" icon="el-icon-delete" @click="removeEvent(calendarDate, idx)" class="event-delete"></el-button>
              </li>
              <li v-if="getEventsByDate(calendarDate).length === 0" class="event-empty">{{$t('dashboard.eventEmpty')}}</li>
            </ul>
          </div>
          <el-dialog :title="$t('dashboard.addEvent')" :visible.sync="showAddEventDialog" width="400px">
            <el-form @submit.native.prevent="addEvent">
              <el-form-item :label="$t('dashboard.eventTitle')">
                <el-input v-model="newEvent.title" maxlength="20" show-word-limit required />
              </el-form-item>
              <el-form-item :label="$t('dashboard.eventType')">
                <el-select v-model="newEvent.type" :placeholder="$t('dashboard.eventType')" style="width: 100%">
                  <el-option :label="$t('dashboard.schedule')" value="schedule" />
                  <el-option :label="$t('dashboard.remind')" value="remind" />
                  <el-option :label="$t('dashboard.holiday')" value="holiday" />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('dashboard.eventContent')">
                <el-input v-model="newEvent.content" type="textarea" :rows="2" maxlength="50" show-word-limit />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="showAddEventDialog = false">{{$t('dashboard.cancel')}}</el-button>
              <el-button type="primary" @click="addEvent">{{$t('dashboard.add')}}</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRemark } from '@/api/shipping'
import { fetchTodoList, createTodo, deleteTodo } from '@/api/user'
import { parseTime } from '@/utils'
import JapaneseHolidays from 'japanese-holidays'

export default {
  name: 'Dashboard',
  data() {
    return {
      localRemarks: [],
      transferRemarks: [],
      localLoading: false,
      transferLoading: false,
      todos: [],
      newTodo: '',
      warningDays: Number(localStorage.getItem('dashboard_warning_days')) || 3,
      calendarDate: new Date(),
      calendarEvents: {},
      showAddEventDialog: false,
      newEvent: { title: '', type: '', content: '' }
    }
  },
  computed: {
    filteredLocalRemarks() {
      return this.localRemarks.filter(item => !item.remark_status)
    },
    filteredTransferRemarks() {
      return this.transferRemarks.filter(item => !item.remark_status)
    },
    warningList() {
      const now = new Date()
      const msPerDay = 24 * 60 * 60 * 1000
      const result = []
      this.localRemarks.forEach(item => {
        if (!item.remark_status) {
          const create = new Date(item.create_time.replace(/-/g, '/'))
          const diff = (now - create) / msPerDay
          if (diff > this.warningDays) {
            result.push({
              type: 'local',
              id: item.fs_no,
              no: item.fs_no,
              create_user: item.create_user,
              create_time: item.create_time
            })
          }
        }
      })
      this.transferRemarks.forEach(item => {
        if (!item.remark_status) {
          const create = new Date(item.create_time.replace(/-/g, '/'))
          const diff = (now - create) / msPerDay
          if (diff > this.warningDays) {
            result.push({
              type: 'transfer',
              id: item.cw_no,
              no: item.cw_no,
              create_user: item.create_user,
              create_time: item.create_time
            })
          }
        }
      })
      return result
    }
  },
  watch: {
    warningDays(val) {
      localStorage.setItem('dashboard_warning_days', val)
    }
  },
  mounted() {
    this.getLocalRemarks()
    this.getTransferRemarks()
    this.loadCalendarEvents()
    this.getTodoList()
    // console.log('JapaneseHolidays结构', JapaneseHolidays)
    // console.log('今天祝日', this.getJpHoliday(new Date()))
  },
  methods: {
    async getTodoList() {
      const res = await fetchTodoList()
      this.todos = res.results || []
    },
    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d}')
    },
    copyText(text) {
      const input = document.createElement('input')
      input.value = text
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    async getLocalRemarks() {
      this.localLoading = true
      try {
        const res = await getRemark()
        this.localRemarks = res.results?.local_order_remark_list || []
      } catch (error) {
        console.error('获取本地单备注失败:', error)
        this.$message.error('获取本地单备注失败')
      } finally {
        this.localLoading = false
      }
    },
    async getTransferRemarks() {
      this.transferLoading = true
      try {
        const res = await getRemark()
        this.transferRemarks = res.results?.transfer_order_remark_list || []
      } catch (error) {
        console.error('获取转运单备注失败:', error)
        this.$message.error('获取转运单备注失败')
      } finally {
        this.transferLoading = false
      }
    },
    refreshLocalRemarks() {
      this.getLocalRemarks()
    },
    refreshTransferRemarks() {
      this.getTransferRemarks()
    },
    async addTodo() {
      const text = this.newTodo && this.newTodo.trim()
      if (!text) return
      try {
        await createTodo({ text })
        this.$message.success('添加成功')
        this.newTodo = ''
        this.getTodoList()
      } catch (e) {
        this.$message.error('添加失败')
      }
    },
    async removeTodo(idx) {
      const item = this.todos[idx]
      if (!item || !item.id) return
      try {
        await deleteTodo(item.id)
        this.$message.success('删除成功')
        this.getTodoList()
      } catch (e) {
        this.$message.error('删除失败')
      }
    },
    isToday(date) {
      const d = new Date()
      return d.toDateString() === date.toDateString()
    },
    getEventsByDate(date) {
      const key = this.formatDate(date)
      return this.calendarEvents[key] || []
    },
    addEvent() {
      const key = this.formatDate(this.calendarDate)
      if (!this.newEvent.title || !this.newEvent.type) {
        this.$message.warning('请填写事项标题和类型')
        return
      }
      if (!this.calendarEvents[key]) this.$set(this.calendarEvents, key, [])
      this.calendarEvents[key].push({
        title: this.newEvent.title,
        type: this.newEvent.type,
        content: this.newEvent.content
      })
      this.saveCalendarEvents()
      this.showAddEventDialog = false
      this.newEvent = { title: '', type: '', content: '' }
    },
    removeEvent(date, idx) {
      const key = this.formatDate(date)
      this.calendarEvents[key].splice(idx, 1)
      if (this.calendarEvents[key].length === 0) delete this.calendarEvents[key]
      this.saveCalendarEvents()
    },
    saveCalendarEvents() {
      localStorage.setItem('dashboard_calendar_events', JSON.stringify(this.calendarEvents))
    },
    loadCalendarEvents() {
      const data = localStorage.getItem('dashboard_calendar_events')
      this.calendarEvents = data ? JSON.parse(data) : {}
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },
    eventTypeLabel(type) {
      if (type === 'schedule') return this.$t('dashboard.schedule')
      if (type === 'remind') return this.$t('dashboard.remind')
      if (type === 'holiday') return this.$t('dashboard.holiday')
      return ''
    },
    eventTypeColor(type) {
      if (type === 'schedule') return '#409EFF'
      if (type === 'remind') return '#F56C6C'
      if (type === 'holiday') return '#67C23A'
      return '#909399'
    },
    changeMonth(type) {
      const d = new Date(this.calendarDate)
      if (type === 0) {
        this.calendarDate = new Date()
      } else {
        d.setMonth(d.getMonth() + type)
        this.calendarDate = new Date(d)
      }
    },
    getJpHoliday(date) {
      const d = (date instanceof Date) ? date : new Date(date)
      if (JapaneseHolidays && typeof JapaneseHolidays.getHolidayName === 'function') {
        return JapaneseHolidays.getHolidayName(d) || ''
      }
      if (JapaneseHolidays && typeof JapaneseHolidays.isHoliday === 'function') {
        return JapaneseHolidays.isHoliday(d) || ''
      }
      return ''
    }
  },
  filters: {
    formatDate(val) {
      if (!val) return ''
      const d = new Date(val)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },
    formatMonth(val) {
      if (!val) return ''
      const d = new Date(val)
      return `${d.getFullYear()}年${d.getMonth() + 1}月`
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  .box-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
    }
    .card-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
    .empty-text {
      text-align: center;
      color: #909399;
      padding: 30px 0;
    }
    .remark-list {
      .remark-item {
        padding: 15px;
        border-bottom: 1px solid #EBEEF5;
        background-color: #fff;
        transition: all 0.3s;
        &:hover {
          background-color: #f5f7fa;
        }
        &:last-child {
          border-bottom: none;
        }
        .remark-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          .order-id {
            font-weight: bold;
            color: #303133;
            .copy-text {
              color: #409EFF;
              cursor: pointer;
              &:hover {
                text-decoration: underline;
              }
            }
          }
          .remark-time {
            color: #909399;
            font-size: 13px;
          }
        }
        .remark-content {
          color: #606266;
          line-height: 1.5;
          word-break: break-all;
          margin-bottom: 10px;
          padding: 10px;
          background-color: #f8f9fb;
          border-radius: 4px;
        }
        .remark-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 8px;
          font-size: 13px;
          .create-user {
            color: #909399;
          }
          .shipping-method {
            padding: 2px 8px;
            border-radius: 4px;
            &.sagawa {
              background-color: #3b499f;
              color: #fff;
            }
            &.yamato {
              background-color: #fdd101;
              color: #000;
            }
          }
        }
      }
    }
  }
  .local-card {
    border-top: 3px solid #409EFF;
  }
  .transfer-card {
    border-top: 3px solid #67C23A;
  }
  .todo-card {
    margin-top: 10px;
    border-top: 3px solid #F56C6C;
    .card-title {
      font-size: 16px;
      font-weight: bold;
      color: #F56C6C;
    }
    .todo-list {
      padding: 10px 0 0 0;
      .todo-input {
        width: 450px;
        margin-bottom: 15px;
      }
      .todo-cards-container {
        display: flex;
        flex-direction: column;
        gap: 10px;
        .todo-card-item {
          background-color: #fff;
          border-radius: 8px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          transition: all 0.3s;
          &:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
          }
          &.done {
            opacity: 0.7;
            text-decoration: line-through;
          }
          .todo-card-content {
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .todo-text {
              flex-grow: 1;
              font-size: 15px;
              color: #303133;
              word-break: break-all;
            }
            .todo-meta {
              display: flex;
              align-items: center;
              .todo-creator {
                font-size: 13px;
                color: #888;
                margin-right: 10px;
              }
              .todo-delete {
                color: #F56C6C;
              }
            }
          }
        }
      }
      .todo-empty {
        color: #bbb;
        text-align: center;
        padding: 20px 0 0 0;
      }
    }
  }
  .warning-row {
    .el-alert {
      background: #fffbe6;
      border: 1px solid #ffe58f;
      position: relative;
      .warning-header {
        position: absolute;
        top: 12px;
        right: 32px;
        display: flex;
        align-items: center;
        z-index: 2;
        .el-input-number {
          margin: 0 6px;
        }
        .warning-tip {
          color: #888;
          font-size: 13px;
        }
      }
      .warning-list {
        margin: 0;
        padding: 0 0 0 20px;
        list-style: disc;
        li {
          margin: 4px 0;
          font-size: 15px;
          color: #d48806;
          .order-type {
            font-weight: bold;
            margin-right: 8px;
          }
          .order-id {
            color: #409EFF;
            margin-right: 8px;
            .copy-text {
              color: #409EFF;
              cursor: pointer;
              &:hover {
                text-decoration: underline;
              }
            }
          }
          .order-user {
            margin-right: 8px;
          }
          .order-date {
            color: #888;
          }
        }
      }
    }
  }
  .calendar-card {
    margin-top: 10px;
    border-top: 3px solid #409EFF;
    .card-title {
      font-size: 16px;
      font-weight: bold;
      color: #409EFF;
    }
    .dashboard-calendar {
      margin-bottom: 20px;
      .calendar-date-cell {
        position: relative;
        min-height: 36px;
        .calendar-date {
          font-size: 15px;
          font-weight: bold;
          &.today {
            color: #F56C6C;
            border-bottom: 2px solid #F56C6C;
          }
        }
        .calendar-events {
          margin: 0;
          padding: 0;
          list-style: none;
          display: flex;
          flex-wrap: wrap;
          li {
            margin-right: 2px;
            .event-dot {
              display: inline-block;
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-top: 2px;
            }
          }
        }
      }
    }
    .calendar-event-panel {
      background: #f8f9fb;
      border-radius: 6px;
      padding: 12px 16px 8px 16px;
      .event-panel-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;
        .el-button {
          margin-left: 10px;
        }
      }
      .event-list {
        list-style: none;
        padding: 0;
        margin: 0;
        li {
          display: flex;
          align-items: center;
          padding: 6px 0;
          .event-dot {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 6px;
          }
          .event-title {
            font-weight: bold;
            margin-right: 6px;
          }
          .event-type {
            color: #888;
            font-size: 13px;
            margin-right: 6px;
          }
          .event-delete {
            color: #F56C6C;
          }
        }
        .event-empty {
          color: #bbb;
          text-align: center;
          padding: 10px 0 0 0;
        }
      }
    }
  }
}

.jp-holiday {
  display: block;
  color: #e74c3c;
  font-size: 12px;
  font-weight: bold;
  margin-top: 2px;
}
</style>
